package com.kun.service.service;

import com.kun.domain.SysRole;
import com.kun.domain.SysUser;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 */
@Component
public class SysPermissionService {

    private final ISysRoleService roleService;

    private final ISysMenuService menuService;

    public SysPermissionService(ISysMenuService menuService, ISysRoleService roleService) {
        this.menuService = menuService;
        this.roleService = roleService;
    }

    /**
     * 获取角色数据权限
     */
    public Set<String> getRolePermission(SysUser user) {
        Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
            return roles;
        }
        roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        return roles;
    }

    /**
     * 获取菜单数据权限
     */
    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
            return perms;
        }
        List<SysRole> roles = user.getRoles();
        if (!CollectionUtils.isEmpty(roles)) {
            // 多角色设置permissions属性，以便数据权限匹配权限
            for (SysRole role : roles) {
                Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                role.setPermissions(rolePerms);
                perms.addAll(rolePerms);
            }
            return perms;
        }
        perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
        return perms;
    }
}
